/**
@author yuntao zhou
reqiure listView.js
*/

if(!QSAPI){
	var QSAPI={};
}

if(!QSAPI.Widget){
	QSAPI.Widget={};
}
QSAPI.Widget.GainerLoserActiveColumns={
	'mostActive':{
        dataIndex: 'Name',
        className: 'column-name',
        align: 'left',
        ellipsis:true,
		dataType:'link'
    },
	'name':{
		dataIndex: 'Name',
		className: 'column-name',
        align: 'left',
		ellipsis:true,
		dataType:'link'
	},
	'upDown':{
        header: '<span style="display:none;">Up/Down</span>',
        dataIndex: 'UpDown',
        className: 'column-updown',
        align: 'right'
    },
	'symbol':{
		dataIndex: 'Symbol',
		className: 'column-symbol',
        align: 'left'
		
	},
	'ticker':{
        dataIndex: 'Symbol',
		className: 'column-symbol',
        align: 'left'
    },
	'last':{
        dataIndex: 'LastPrice',
		className: 'column-lastprice',
        align: 'right',
		dataType: 'float'
    },
	'chg':{
        dataIndex: 'Chg',
        align: 'right',
        className: 'column-chg',
        dataType: 'float'
	},
	'gain/Loss%':{
        dataIndex: 'Chg%',
        className: 'column-chgpc',
        align: 'right',
        dataType: 'float'
    },
	'chg%':{
        dataIndex: 'Chg%',
        className: 'column-chgpc',
        align: 'right',
        dataType: 'float'
    },
	'open':{
        dataIndex: 'OpenPrice',
        className: 'column-open',
        align: 'right',
        dataType: 'float'
	},
	'high':{
        dataIndex: 'HighPrice',
        className: 'column-high',
        align: 'right',
        dataType: 'float'
	},
	'low':{
        dataIndex: 'LowPrice',
        className: 'column-high',
        align: 'right',
        dataType: 'float'
    },
	'volume':{
        dataIndex: 'Volume',
        className: 'column-volumn',
        align: 'right',
        dataType: 'float'
	}
};
QSAPI.Widget.BaseGainerLoserActive=function(){
	this.html='<div class="qs-gla"><div class="hd clearfix"></div><div class="bd"><div class="data clearfix"></div></div></div>';
	this.listViews={};
	this.MSTATSTicker='MSTATS_ALL_MJ';
	this.MSTATSTickerMap={
        1:'MSTATS_AMX_L_MJ',
        14:'MSTATS_NYS_L_MJ',
        16:'MSTATS_ARC_L_MJ',
        19:'MSTATS_NAS_L_MJ',
        127.1:'MSTATS_TSX_MJ',
        127.2:'MSTATS_VEN'
    };
	this.tokens={D1902:QS_Lang.marketGLA['d1902'],D1900:QS_Lang.marketGLA['d1900'],D1903:QS_Lang.marketGLA['d1903'],D1901:QS_Lang.marketGLA['d1901'],D1904:QS_Lang.marketGLA['d1904']};
	this.mainTickers={};
    this.subTickers={};
	this.mainIntervalObj=null;
    //this.mianIntervalTime=60000;
	this.config={
		suffix:'',
		batchSize:50,
        maxCount:10,
		frequency:60000,
        needReplaceExternalSymbol:false,
        quoteURL:QSAPI.getQSPullPath()+'getGLAQuoteData1.jsp',
        //showHead:false,
        width:0,
        height:0,
        fixHeight:true,
        clickable:true
    };
	this.callback={};
    this.loaded=false;
    this.lastCallbackHeight=0;
};

QSAPI.Widget.BaseGainerLoserActive.prototype={
	setClickClass:function(clickable){
		if(this.el&&!clickable){
			this.el.addClass('unclickable');
		}
	},
	createCols:function(colsWidth){
		var customColumns=[{
	        header: "gkey",
	        dataIndex: 'gkey',
	        hide: true
	    }];
		for(var field in colsWidth){
			var col={};
			$.extend(true,col,QSAPI.Widget.GainerLoserActiveColumns[field]);
			if(!col.header){
				col.header=QS_Lang.marketGLA[field.toLowerCase()];
			}
			col.width=colsWidth[field];
			customColumns.push(col);
		}
		return customColumns;
	},
	_getExternalSymbol:function(symbols,callback){
        checkTickerInfo(symbols,function(data){
            if ((!data || !data.Records || data.Records.length < 1)) return;
            var sybmolmap={};
            var rs, lg = data.Records.length,tenforeCode,tenforeTicker;
            for (var i = 0; i < lg; i++) {
               rs = data.Records[i];
               if(rs.ClientTicker&&rs.QueryKey&&rs.TenforeInfo){
                     tenforeCode=  rs.TenforeInfo[1]; 
                     tenforeTicker =  rs.TenforeInfo[0];
                    if (tenforeCode&&tenforeTicker) {
                        tenforeCode=tenforeCode<126?126:tenforeCode;
                        sybmolmap[tenforeCode + ":" +tenforeTicker] = {
                            ticker: rs.ClientTicker,
                            name: rs.Name || ''
                        }
                    }
               }
            }
            callback(sybmolmap);
        });
    },
	_forceUpdateData:function(listView){
		var ids=listView.getIDs(),gkey,d,oData;
        for(var i=0,l=ids.length;i<l;i++){
            gkey=ids[i];
            d=this.subTickers[gkey];
            if(d){
                oData={
                    LastPrice:{
                        value:d["LastPrice"],
                        oVlaue:null,
                        dataType:'f'
                    },
                    Chg:{
                        value:d["Chg"],
                        oVlaue:null,
                        dataType:'f'
                    },
                    Volume:{
                        value:d["Volume"],
                        oVlaue:null,
                        dataType:'f'
                    },
                    HighPrice:{
                        value:d["HighPrice"],
                        oVlaue:null,
                        dataType:'f'
                    },
                    LowPrice:{
                        value:d["LowPrice"],
                        oVlaue:null,
                        dataType:'f'
                    },
                    Name:{
                        value:d["Name"]||this._formatNameString(gkey.split(":")[1])||'',
                        oVlaue:null,
                        dataType:'s'
                    }
                };
                oData["Chg%"]={
                    value:d["Chg%"],
                    oVlaue:null,
                    dataType:'f'
                };
                listView.updateData(gkey,oData);
            }else{
                continue;
            }
        }
	},
	_mainCallback:function(o){
        window.GLAData = {
            main: this.mainTickers,
            sub: this.subTickers
        };
        var self=this;
		o=o||{};
        var items=o.items,needSubTciekrs=[],needSearchExSymbol=[];
        if(items&&items.length>0){
            var exch,gkey,fields,symbol;
            for(i=0,l=items.length;i<l;i++){
                symbol=items[i].symbol;
                exch=items[i].service;
                gkey=exch+":"+symbol.split("|")[1];
                if(!this.mainTickers[gkey]){
                    this.mainTickers[gkey]={};
                }
                exch=this.genExchange(exch);//quote data from 126 composive exchange
                fields=items[i].fields;
                var fieldName,fieldValue,token,gridData;
                if(fields.length>0){
                    for(var j=0,jl=fields.length;j<jl;j++){
                        gridData=[];
                        fieldName=fields[j].name;
                        fieldValue=fields[j].value;
                        if((fieldName=='D1900'||fieldName=='D1901'||fieldName=='D1902'||fieldName=='D1903'||fieldName=='D1904')&&$.inArray(fieldName,this.visibleTokens)>-1){
                            token=fieldName;
                            var oldFieldValue=this.mainTickers[gkey][fieldName];
                            if(oldFieldValue==fieldValue){
                                continue;
                            }
                            var subTickers=fieldValue.split(",");
                            var subKey;
                            var len=subTickers.length>this.config.maxCount?this.config.maxCount:subTickers.length;

                            if (oldSubTickers) {
                                 var oSubKey,oldSubTickers=oldFieldValue.split(",");
                                for (var m = 0; m < len; m++) {// delete old tickers
                                   oSubKey=exch+":"+oldSubTickers[m];
                                    delete this.subTickers[oSubKey]['tokens'][token];//delete old grid 
                                    if ($.isEmptyObject(this.subTickers[oSubKey]['tokens'])) {
                                        delete this.subTickers[oSubKey];
                                    }
                                }
                            }
                            
                            for(var k=0;k<len;k++){
                                subKey=exch+":"+subTickers[k];
                                var pullkey=exch + ".1." + subTickers[k];
                                if ($.inArray(pullkey, needSubTciekrs) < 0) {// remove duplicate subticker
                                    needSubTciekrs.push(pullkey);
                                }
                                if(!this.subTickers[subKey]){// subscribe new ticker
                                    this.subTickers[subKey]={};
                                }
                                
                                if(!this.subTickers[subKey]['tokens']){
                                    this.subTickers[subKey]['tokens']={};
                                }
                                if(!this.subTickers[subKey]['tokens'][token]){
                                    this.subTickers[subKey]['tokens'][token]=1;
                                }
                                gridData.push({
                                    gkey:subKey,
                                    Symbol:subTickers[k]+this.config.suffix,
                                    Name:this.subTickers[subKey].Name||this._formatNameString(subTickers[k])||''
                                });
                            }
                            this.mainTickers[gkey][fieldName]=fieldValue;
                            if (this.listViews[exch][token]) {
                                this.listViews[exch][token].reBindData(gridData);
                                this._forceUpdateData(this.listViews[exch][token]);
                            }
                        }else{
                            continue;
                        }
                    }
                }
            }
        }
        if (needSubTciekrs.length>0) {
            var para={
                tickers:needSubTciekrs
            };
            this._quoteTickers(para, function(body){
                self._subCallback(body);
                self._replaceClientSymbol();
            });
        }
    },_subCallback:function(o){
        var items=o.items;
        if ($.isArray(items)) {
            for (var i = 0, l = items.length; i < l; i++) {
                var needUpdateField = {};
                var symbol = items[i].symbol;
                var service = items[i].service;
                var fields = items[i].fields;
                var gkey = service + ":" + symbol.split("|")[1];
                var subTicker = this.subTickers[gkey];
                if (!subTicker) {
                    continue;
                }
                for (var j = 0, jl = fields.length; j < jl; j++) {
                    var fieldName = fields[j].name;
                    var oldValue = subTicker[fieldName];
                    var value = fields[j].value;
                    var ty = 's';
                    if (fieldName == "LastPrice" || fieldName == "ClosePrice" || fieldName == "AfterTPrice" || fieldName == "Volume" || fieldName == "HighPrice" || fieldName == "LowPrice") {
                        value = parseFloat(value, 10);
                        ty = 'f';
                    }
                    else 
                        if (fieldName == "AfterTDate" || fieldName == "TradeDate") {
                            value = this._formatDateString(value);
                            ty = 's';
                        }
                        else 
                            if (fieldName == "AfterTTime" || fieldName == "TradeTime") {
                                value = parseInt(value, 10);
                                ty = 'i';
                            }
                            else 
                                if (fieldName == "Name") {
                                    value = this._formatNameString(value);
                                }
                    if (oldValue != value) {
                        needUpdateField[fieldName] = {
                            value: value,
                            oValue: oldValue,
                            dataType: ty
                        };
                        subTicker[fieldName] = value;
                    }
                }
                var chg, chgp;
                if (!this._isAfter(subTicker['AfterTDate'], subTicker['AfterTTime'], subTicker['TradeDate'], subTicker['TradeTime'])) {
                    if (subTicker['LastPrice'] > 0 && subTicker['ClosePrice'] > 0 && (needUpdateField['LastPrice'] || needUpdateField['ClosePrice'])) {
                        chg = subTicker['LastPrice'] - subTicker['ClosePrice'];
                        chgp = chg / subTicker['ClosePrice'] * 100;
                        if (chg != subTicker['Chg']) {
                            needUpdateField['Chg'] = {
                                value: chg,
                                oValue: subTicker['Chg'],
                                dataType: 'f'
                            };
                            needUpdateField['Chg%'] = {
                                value: chgp,
                                oValue: subTicker['Chg%'],
                                dataType: 'f'
                            };
                            subTicker['Chg%'] = chgp;
                            subTicker['Chg'] = chg;
                        }
                    }
                }
                else {
                    if (subTicker['AfterTPrice'] > 0 && subTicker['LastPrice'] > 0 && (needUpdateField['AfterTPrice'] || needUpdateField['LastPrice'])) {
                        chg = subTicker['AfterTPrice'] - subTicker['LastPrice'];
                        chgp = chg / subTicker['LastPrice'] * 100;
                        if (chg != subTicker['Chg']) {
                            needUpdateField['Chg'] = {
                                value: chg,
                                oValue: subTicker['Chg'],
                                dataType: 'f'
                            };
                            needUpdateField['Chg%'] = {
                                value: chgp,
                                oValue: subTicker['Chg%'],
                                dataType: 'f'
                            };
                            subTicker['Chg%'] = chgp;
                            subTicker['Chg'] = chg;
                        }
                    }
                }
                for (var token in subTicker.tokens) {
                    for (var exch in this.listViews) {
                        if (!this.listViews[exch][token]) {
                            continue;
                        }
                        if (!subTicker['Gid']) {// add the style for invalid symbol
                            var DOMMap = this.listViews[exch][token].getDOMMap();
                            if (DOMMap[gkey]) {
                                $(DOMMap[gkey]['Symbol']).parent('.column-symbol').addClass('column-invalid');
                                $(DOMMap[gkey]['Name']).parent('.column-name').addClass('column-invalid');
                            }
                        }
                        if (!$.isEmptyObject(needUpdateField)) {
                            this.listViews[exch][token].updateData(gkey, needUpdateField);
                        }
                    }
                }
            }
        }

		if(this.el.height()!=this.lastCallbackHeight){
			this.changeOutSize(this.config.width,this.config.height);
		}
    },
    _replaceClientSymbol:function(){
        var self=this;
        if(!this.config.needReplaceExternalSymbol){
            return;
        }
        var tickers=[],subTicker;
        for(var gkey in this.subTickers){
            subTicker=this.subTickers[gkey];
            if(!subTicker.replaced&&subTicker['Gid']){
                tickers.push(subTicker['Gid']);
            }
        }
        if(tickers.length>0){
            this._getExternalSymbol(tickers,function(o){                
                for(var k in self.subTickers){
                    self.subTickers[k].replaced=true;
                    if(o[k]){
                        self.subTickers[k].ClientTicker=o[k].ticker;
                        self.subTickers[k].Name=o[k].name;
                        for (var exch in self.listViews) {
                            for (var t in self.tokens) {
                                if (self.subTickers[k]["tokens"][t] == 1) {
                                    self.listViews[exch][t].updateData(k, {
                                        Symbol: {
                                            value: o[k].ticker,
                                            dataType: 's',
                                            oVlaue: null
                                        }
                                    })
                                }
                            }
                        }
                    }
                }
            });
        }
    },
    _isAfter:function(ad,at,td,tt){
        if(!ad||!at){
            return false;
        }
        if(!td||!tt){
            return true;
        }
        return (parseFloat(ad+at)-parseFloat(td+tt))>0;
    },
    startMainAutoUpdate:function(){
        var self=this;
        if (this.mainIntervalObj == null) {
            this.mainIntervalObj = setInterval(function(){
                if (!$.isEmptyObject(self.mainTickers)) {
                var arr = [];
                for (var mainKey in self.mainTickers) {
                    arr.push(mainKey.split(":")[0] + ".1." + mainKey.split(":")[1]);
                }
                self.quoteMainTickers(arr);
                }
            }, this.config.frequency);
        }
    },
    stopMainAutoUpdate:function(){
        if(this.mainIntervalObj!=null){
            clearInterval(this.mainIntervalObj);
            this.mainIntervalObj=null;
        }
    },
    _quoteTickers:function(para,callback){
		var tickers=para.tickers;
		if(tickers.length>this.config.batchSize){
			var c=Math.ceil(tickers.length/this.config.batchSize);
			var cbNum=0;
			var returnItems=[];
			for(var i = 0; i < c; i++){
				para.tickers=tickers.slice(this.config.batchSize*i,this.config.batchSize*(i+1)).join(',');
				$.getJSON(this.config.quoteURL+"?cb=?",para,function(o){
					cbNum++;
					if(typeof o!='undefined'&&typeof o.items!='undefined'){
						returnItems = returnItems.concat(o.items); //merge the return
					}
					if(cbNum>=c){
						callback({
							'items':returnItems
						})
					}
				});
			}
		}else{
			para.tickers=tickers.join(',');
			$.getJSON(this.config.quoteURL+"?cb=?",para,callback);
		}
    },
    quoteMainTickers:function(mainTickers){
        var self=this;
        var para={
            tickers:mainTickers
        };
        if(this.visibleTokens.length!=0){
            para["tokens"]=this.visibleTokens.join(",");//.replace(/D/g,"")
        }
        this._quoteTickers(para,function(o){
            self._mainCallback(o);
        });
    },
    startSubAutoUpdate:function(){
        var self=this;
        if (this.subIntervalObj == null) {
            this.subIntervalObj = setInterval(function(){
                if (!$.isEmptyObject(self.subTickers)) {
                    var arr = [];
                    for (var subKey in self.subTickers) {
                        arr.push(subKey.split(":")[0] + ".1." + subKey.split(":")[1]);
                    }
                    self._quoteTickers({
                        tickers: arr
                    }, function(o){
                        self._subCallback(o);
                    });
                }
            }, this.config.frequency);
        }
    },
    stopSubAutoUpdate:function(){
        if(this.subIntervalObj!=null){
            clearInterval(this.subIntervalObj);
            this.subIntervalObj=null;
        }
    },
	_getPIDFromRowData:function(row){
		var gkey=row.data["gkey"];
        var d=this.subTickers[gkey];
        var symbol;
        if(d){
            symbol=d["Gid"];
        }
		return symbol;
	},
    createListViews:function(container,exch,tokens,columns){
        var self=this;
        for(var i=0,l=tokens.length;i<l;i++){
            if(typeof this.listViews[exch]=='undefined') {
                this.listViews[exch] = {};
            }
            this.listViews[exch][tokens[i]]=new QSAPI.Widget.ListView(container,columns,$.extend(true,{title:this.tokens[tokens[i]],token:tokens[i],exch:exch},this.config),{
                onCellClick:function(e,cell,row){
                    if(!self.config.clickable||(cell.key!='Symbol'&&cell.key!='Name')){
                        return;
                    }
                    var symbol=self._getPIDFromRowData(row);
					if(!symbol){
						return;
					}
                    if(typeof self.callback.customTickerClick=='function'){
                        self.callback.customTickerClick(symbol);
                    }
                },
				onCellMouseover:function(e,cell,row){
					if(self.config.clickable&&cell.key=='Symbol'&&self._getPIDFromRowData(row)){
                        cell.el.addClass("hover");
                    }
				},
				onCellMouseout:function(e,cell,row){
                    if(self.config.clickable&&cell.key=='Symbol'&&self._getPIDFromRowData(row)){
                        cell.el.removeClass("hover");
                    }
                }
            });
        }        
    },
	changeOutSize:function(w,h){
		/*var curHeight=this.el.height();
		if(curHeight==this.lastCallbackHeight){
			return;
		}*/
        var parent = this.el.parent();
        w = w>0?w:parent.width();
        h = h>0?h:parent.height();
        var size={};
        size.width=w;
        if(this.config.fixHeight){
            size.height=h;
        }
        this.el.css(size);
        if (this.scrollPN != null) {
            this.scrollPN.reSize(null, h - this.headHeight);
        }
        for(var k in this.listViews){
            for (var t in this.listViews[k]) {
                this.listViews[k][t].grid.ellipsisDom();
            }
        }
        this.onHeightChange(this.el.height());
    },
    onHeightChange:function(height){
        if (!this.loaded) {
            this.lastCallbackHeight = height;
            this.loaded = true;
            if (typeof this.callback.onLoad == 'function') {
                this.callback.onLoad({
                    component: 'gla',
                    height: height,
                    minWidth:this.minWidth
                });
            }
        }else {
            if (this.lastCallbackHeight != height) {
                this.lastCallbackHeight = height;
                if (typeof this.callback.onHeightChange == 'function') {
                    this.callback.onHeightChange({
                        height: this.lastCallbackHeight,
                        component: 'gla'
                    });
                }
            }
        }
    },
    genExchange:function(exch){
        return exch<126?126:exch;
    },
    clear:function(){
        this.startMainAutoUpdate();
        this.startSubAutoUpdate();
        for(var p in this){
            if(!p || p == 'clear'){continue;}
            this[p] = null;
            delete this[p];
       }
    },
	_formatDateString:function(str){// yyyymmdd to yyyy-mm-dd
		var t = [];
		t.push(str.slice(0,4)),t.push(str.slice(4,6)),t.push(str.slice(6,8));
		return t.join("-");
	},
	_formatNameString :function(str){
		if(str==''||str==null){
			return str;
		}
		var t=str.split(" ");
		var t1=[];
		for(var i=0,l=t.length;i<l;i++){
			var firstChar=t[i].substring(0,1);
			var otherChars=t[i].substring(1);
			t1.push(firstChar.toUpperCase()+otherChars.toLowerCase());
		}
		return t1.join(" ");
	}
};


QSAPI.Widget.TabedGainerLoserActive=function(container,config,callback,id){
	QSAPI.Widget.BaseGainerLoserActive.call(this);
	this.container=container;
	var cfg={
		showHead:true,
        tokens:"D1902,D1900,D1903,D1901,D1904",
        hideTitle:true,
		activeTabId:null,
		clickable:true
	};
	$.extend(this.config,cfg,config);
	$.extend(this.callback,callback);
	this.id=this.subscribeID=id;
	this.customColumns=null;
	this.colsWidth={
		'name':'19%',
		'symbol':'10%',
		'last':'10%',
		'open':'10%',
		'chg':'9%',
		'chg%':'9%',
		'high':'10%',
		'low':'10%',
		'volume':'12%'
	};
    if(this.config.colsWidth){
        this.colsWidth=this.config.colsWidth;
    }
    this.headHeight=0;
    this.tabmenu=null;
    this.scrollPN=null;
	this.init();
};

QSAPI.Widget.TabedGainerLoserActive.prototype=new QSAPI.Widget.BaseGainerLoserActive();
$.extend(QSAPI.Widget.TabedGainerLoserActive.prototype,{
	init:function(){
		this.customColumns=this.createCols(this.colsWidth);
        this.el=$(this.html).addClass('qs-gla-tab').appendTo(this.container);
		this.setClickClass(this.config.clickable);
        var headEl=this.el.find('.hd');
        this._createTab(headEl);
        if (this.config.fixHeight) {
			this.scrollPN = new Util.ScrollPanel(this.el.find('.data'),{
                 delayRun: false
            });
        }
        if(!this.config.showHead){
            headEl.hide();
        }
        this.headHeight=headEl.outerHeight(true);
    },
    changeExchange:function(exchange){
		if(exchange!=null&&this.config.exchange!=exchange){
			this.config.exchange=exchange;
			this.tabmenu.currentTab = null;
			if(this.visibleTokens.length>0){
				this.empty(this.visibleTokens[0]);
			}
			this.tabmenu.changeTabById(this.visibleTokens[0],true);
		}
    },
    _genTokensData:function(){
        var data=[],at=this.config.tokens.split(",");
        for(var i=0,l=at.length;i<l;i++){
            data.push({
                id: at[i],
                txt: this.tokens[at[i]],
                closable: false
            });
        }
        return data;
    },
    _createTab:function(container){
        var self = this;
        this.tabmenu = new Util.TabMenu(container, this._genTokensData(), {
            onActive: function(tab){
                self.visibleTokens=[tab.id];
                self.subscribeNewExch(tab.id);
				if(typeof self.callback.onGroupChange=='function'){
					self.callback.onGroupChange(tab.id);
				}
            },
            onDeActive: function(tab){
                self.empty(tab.id);
            }
        }, {
            tabsList: false,
            activeAtInit: true,
            autoSlideToActiveTab:true,
			activeTabId:this.config.activeTabId
        });
    },
    subscribeNewExch:function(token){
		if(this.config.exchange==null)return;
        var exch=Math.floor(this.config.exchange);
        this.createListViews(this.el.find('.data'),this.genExchange(exch),[token],this.customColumns);
        var MSTATSTicker=this.MSTATSTickerMap[this.config.exchange]?this.MSTATSTickerMap[this.config.exchange]:this.MSTATSTicker;
		var mainKey=exch+":"+MSTATSTicker;
        var mainTickers=exch+".1."+MSTATSTicker;
        this.mainTickers[mainKey]={};
        this.quoteMainTickers([mainTickers]);
        this.startMainAutoUpdate();
        this.startSubAutoUpdate();
    },
    empty:function(token){       
        this.mainTickers={};
        this.subTickers={};
        this.stopMainAutoUpdate();
        this.stopSubAutoUpdate();
        this.el.find('.data')[0].innerHTML='';
        if (typeof token == 'undefined') {
            this.listViews={};
        }else {
			var exch=this.genExchange(Math.floor(this.config.exchange));
			if(this.listViews[exch]){
				delete this.listViews[exch][token];
			}
        }
    },
	setSuffix:function(suffix){
		this.config.suffix=suffix;
	}
});

QSAPI.Widget.GainerLoserActive=function(container,config,callback,id){
	this.shortNameExchMap={
		'TSX':{code:'127.1',suffix:'-C'},
		'TSXV':{code:'127.2',suffix:'-C'},
		'AMEX':{code:'1',suffix:'-U'},
		'NYSE':{code:'14',suffix:'-U'},
		'ARCA':{code:'16',suffix:'-U'},
		'NASDAQ':{code:'19',suffix:'-U'}
	};
	this.container = typeof container=='string'? $(container):container;
	this.id=this.subscribeID=id;
	this.config={
		type:'tab',
		needSuffix:false
	}
	this.callback={};
    if(config){
        $.extend(this.config,config);
    }
	
	if(this.config.exchange){
		this.config.suffix=this._getSuffix(this.config.exchange);
		this.config.exchange=this._getTenforeExchByShortName(this.config.exchange);
	}
	if(this.config.activeGroup){
		this.config.activeTabId=this.config.activeGroup;
	}
	if(typeof this.config.sortable=='boolean'){
		if(!this.config.gConfig){
			this.config.gConfig={};
		}
		this.config.gConfig.sortable=this.config.sortable;
	}
    if(callback){
        $.extend(this.callback,callback);
    }
	
	this.glaWidget=null;
	
	this.init();
};

QSAPI.Widget.GainerLoserActive.prototype={
	init:function(){
		if(this.config.type=='tab'){
            this.glaWidget=new QSAPI.Widget.TabedGainerLoserActive(this.container,this.config,this.callback,this.id);
        }
	},
	changeExchange:function(shortName){
		var exchange=this._getTenforeExchByShortName(shortName);
		this.glaWidget.setSuffix(this._getSuffix(shortName));
		this.glaWidget.changeExchange(exchange);
	},
	changeOutSize:function(w,h){
        if(this.glaWidget!=null){
            this.glaWidget.changeOutSize(w,h);
        }
    },
	clear:function(){
       if(typeof this.callback.beforeClear=='function'){
           this.callback.beforeClear();
       }
       if(this.glaWidget){
           this.glaWidget.clear();        
       }
       for(var p in this){
            if(!p || p == 'clear'){continue;}
            this[p] = null;
            delete this[p];
       }
    },
	_getSuffix:function(shortName){
		if(this.config.needSuffix){
			return shortName&&this.shortNameExchMap[shortName]?this.shortNameExchMap[shortName]['suffix']:'';
		}else{
			return '';
		}
		
	},
	_getTenforeExchByShortName:function(shortName){
		return shortName&&this.shortNameExchMap[shortName]?this.shortNameExchMap[shortName]['code']:null;
	}
};